package com.admission.web.admin;

import java.util.List;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.admission.model.Authority;
import com.admission.model.Role;
import com.admission.service.RoleManager;
import com.admission.util.HibernateUtils;
import com.admission.web.CrudActionSupport;

@Namespace("/admin")
@Results({ @Result(name = CrudActionSupport.RELOAD, location = "role-admin.action", type = "redirect") })
public class RoleAdminAction extends CrudActionSupport<Role> {

	private static final long serialVersionUID = 3909764619067254237L;
	private String id;
	private String ids;
	private Role entity;
	private RoleManager roleManager;
	private List<Role> allRoleList;// 角色列表
	private List<String> checkedAuthIds;// 页面中钩选的权限id列表

	public Role getModel() {
		return entity;
	}

	@Override
	public String list() throws Exception {
		allRoleList = roleManager.getAllRole();
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		checkedAuthIds = entity.getAuthIds();
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		if (!entity.getId().equals("1")) {
			HibernateUtils.mergeByCheckedIds(entity.getAuthorities(),
					checkedAuthIds, Authority.class);
		}
		// 保存用户并放入成功信息.
		roleManager.saveRole(entity);
		addActionMessage("保存角色成功");
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		roleManager.deleteRole(ids);
		return RELOAD;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (!StringUtils.isEmpty(id)) {
			entity = roleManager.getRole(id);
		} else {
			entity = new Role();
		}

	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public Role getEntity() {
		return entity;
	}

	public void setEntity(Role entity) {
		this.entity = entity;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	public List<Role> getAllRoleList() {
		return allRoleList;
	}

	public void setAllRoleList(List<Role> allRoleList) {
		this.allRoleList = allRoleList;
	}

	public List<String> getCheckedAuthIds() {
		return checkedAuthIds;
	}

	public void setCheckedAuthIds(List<String> checkedAuthIds) {
		this.checkedAuthIds = checkedAuthIds;
	}

	/**
	 * input页面显示所有授权列表.
	 */
	public List<Authority> getAllAuthorityList() {
		return roleManager.getAllAuthority();
	}

}
